/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-09-15 16:14:33
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-09-15 16:20:14
 * @FilePath: \vue-sound\simple-proxy.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 简单的本地代理服务器
const http = require('http')
const https = require('https')
const url = require('url')

const PORT = 3002

const server = http.createServer((req, res) => {
  // 设置CORS头
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
  
  if (req.method === 'OPTIONS') {
    res.writeHead(200)
    res.end()
    return
  }
  
  // 解析请求URL
  const parsedUrl = url.parse(req.url, true)
  const targetUrl = parsedUrl.query.url
  
  if (!targetUrl) {
    res.writeHead(400)
    res.end('Missing url parameter')
    return
  }
  
  console.log('代理请求:', req.method, targetUrl)
  
  // 解析目标URL
  const target = url.parse(targetUrl)
  const options = {
    hostname: target.hostname,
    port: target.port || (target.protocol === 'https:' ? 443 : 80),
    path: target.path,
    method: req.method,
    headers: {
      ...req.headers,
      host: target.hostname
    }
  }
  
  // 选择协议
  const client = target.protocol === 'https:' ? https : http
  
  const proxyReq = client.request(options, (proxyRes) => {
    console.log('代理响应:', proxyRes.statusCode)
    
    // 设置响应头
    res.writeHead(proxyRes.statusCode, proxyRes.headers)
    
    // 转发响应数据
    proxyRes.pipe(res)
  })
  
  proxyReq.on('error', (error) => {
    console.error('代理请求错误:', error)
    res.writeHead(500)
    res.end('Proxy request failed')
  })
  
  // 转发请求数据
  req.pipe(proxyReq)
})

server.listen(PORT, () => {
  console.log(`代理服务器运行在 http://localhost:${PORT}`)
  console.log('使用方法: http://localhost:3002/?url=https://aip.baidubce.com/oauth/2.0/token')
})
